package com.ssh.controller;

import com.ssh.Dto.LoginDto;
import com.ssh.Dto.UserDto;
import com.ssh.entity.Bzdm;
import com.ssh.entity.Depart;
import com.ssh.entity.User;
import com.ssh.service.BzdmService;
import com.ssh.service.DepartService;
import com.ssh.service.UserService;
import com.ssh.util.R;
import com.ssh.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private BzdmService bzdmService;
    @Autowired
    private DepartService departService;

    @RequestMapping("/getAllUser")
    @ResponseBody
    public R getAllUser(
            @RequestParam(required = false) String username,
                        @RequestParam(required = false) String yhbm) {
        Map<String, Bzdm> bzdmMap = bzdmService.getAllBzdm().stream().collect(Collectors.toMap(k -> k.getCode(), v -> v));
        Map<String, Depart> departMap = departService.getAllDepart().stream().collect(Collectors.toMap(k -> k.getBmdm(), v -> v));
        List<UserVO> collect = userService.getAllUser(username,yhbm).stream().map(user -> {
            UserVO userVO = new UserVO();
            userVO.setYhxm(user.getYhxm());
            userVO.setYhid(user.getYhid());
            userVO.setSex(bzdmMap.get(user.getYhxb()).getMc());
            userVO.setDepart(departMap.get(user.getYhbm()).getBmmc());
            return userVO;
        }).collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();

        map.put("list", collect);
        return R.success().data(map);
    }

    @RequestMapping("/login")
    public ModelAndView login(LoginDto loginDto, HttpServletResponse response) {
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        user.setYhid(loginDto.getUsername());
        user.setYhkl(loginDto.getPassword());
        boolean check = checkUserNamePassword(user);
        if (check) {
            if (1 == loginDto.getRemember()) {
                Cookie uname = new Cookie("username", loginDto.getUsername());
                Cookie pwd = new Cookie("password", loginDto.getPassword());
                // 设置cookie过期时间为 7 天 单位 秒
                uname.setMaxAge(7*24*60*60);
                pwd.setMaxAge(7*24*60*60);
                uname.setPath("/");
                pwd.setPath("/");
                response.addCookie(uname);
                response.addCookie(pwd);
            }
            List<UserVO> collect = getUserVOS();
            modelAndView.setViewName("/list");
            modelAndView.addObject("userList", collect);
            List<Depart> allDepart = departService.getAllDepart();
            modelAndView.addObject("departList", allDepart);

        } else {
            modelAndView.setViewName("/index");
            modelAndView.addObject("errMessage", "用户名或密码错误");
        }
        return modelAndView;


    }

    @RequestMapping("/toDetail")
    public ModelAndView toDetail(User user) {
        ModelAndView modelAndView = new ModelAndView();
        List<Bzdm> bzdmList = bzdmService.getAllBzdm().stream().collect(Collectors.toList());
        List<Depart> departList = departService.getAllDepart().stream().collect(Collectors.toList());
        modelAndView.addObject("sexList",bzdmList);
        modelAndView.addObject("departList",departList);
        modelAndView.setViewName("detail");
        return modelAndView;


    }
    @ResponseBody
    @RequestMapping("/save")
    public R save(UserDto userDto) {
        String yhid = userDto.getUserId();
        User user = userService.get(yhid);
//        if (!Objects.isNull(user)) {
//            return R.fail().msg("用户userId已存在");
//        }
        user = new User();
        user.setYhid(userDto.getUserId());
        user.setYhdm(userDto.getId());
        user.setYhxm(userDto.getUsername());
        user.setCsrq(userDto.getDate());
        user.setYhkl(userDto.getPassword());
        user.setYhbm(userDto.getDepart());
        user.setYhxb(userDto.getSex());
        user.setPxh(userDto.getSortNum());
        user.setSfjy(userDto.getSfjy());
        userService.save(user);
        return R.success().msg("新增成功");


    }




    @ResponseBody
    @RequestMapping( value = "/delete/{yhid}",method = RequestMethod.POST)
    public R delete(@PathVariable("yhid") String yhid) {
        userService.delete(yhid);
        return R.success().msg("删除成功");


    }
    @RequestMapping( value = "/logout")
    public void logout(HttpServletResponse response) {
        Cookie username = new Cookie("username", null);
        Cookie password = new Cookie("password", null);
        username.setMaxAge(0);
        password.setMaxAge(0);
        username.setPath("/");
        password.setPath("/");
        response.setStatus(302);
        response.addCookie(username);
        response.addCookie(password);
        response.setHeader("Location","http://localhost:8080/views/index.jsp");
    }

    private boolean checkUserNamePassword(User user) {
        User u = userService.get(user.getYhid());
        if (!Objects.isNull(u) && u.getYhkl().equals(user.getYhkl().trim())) {
            return true;
        }
        return false;
    }

    public List<UserVO> getUserVOS() {
        Map<String, Bzdm> bzdmMap = bzdmService.getAllBzdm().stream().collect(Collectors.toMap(k -> k.getCode(), v -> v));
        Map<String, Depart> departMap = departService.getAllDepart().stream().collect(Collectors.toMap(k -> k.getBmdm(), v -> v));
        List<User> allUser = userService.getAllUser(null,null);
        return allUser.stream().map(user -> {
            UserVO userVO = new UserVO();
            userVO.setYhxm(user.getYhxm());
            userVO.setYhid(user.getYhid());
            userVO.setSex(bzdmMap.get(user.getYhxb()).getMc());
            userVO.setDepart(departMap.get(user.getYhbm()).getBmmc());
            return userVO;
        }).collect(Collectors.toList());
    }
}
